from typing import Optional

import PySide6.QtWidgets
from PySide6.QtCore import QSize
from PySide6.QtWidgets import (QAbstractItemView, QSizePolicy, QTreeWidget,
                               QTreeWidgetItem, QWidget)

from ....PSData import *


class IWTreeWidgetDisplay(QTreeWidget, PSDataServer):
    '''
    类说明：
        一个树形显示窗体的框架
    '''
    def __init__(self, parent: Optional[PySide6.QtWidgets.QWidget] = ...) -> None:
        super().__init__(parent=parent)
        self._widgetTable = dict()
        self.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
        # 设置缩进
        self.setIndentation(10)
        self.setAnimated(True)
        
    def InsertWidget(self, widget: 'QWidget', title: 'str' = '', height: 'int' = 500, index: 'int' = -1, ) -> None:
        '''
        Function:
            在指定的位置插入一个窗体
        args:
            widget: 'QWidget' 要插入的窗体对象
            title: 'str' 插入窗体的名称
            index: 'int' 从哪个位置插入，默认情况下是插入到最后面
        return:
            None
        '''
        title_ = title
        if (title_ == ''):
            title_ = widget.windowTitle()
        if (title_ in self._widgetTable.keys()):
            raise KeyError('TreeWidgetDisplay already has widget {0}'.format(title_))
        item_title_ = QTreeWidgetItem()
        item_title_.setText(0, title_)
        if (index < 0):
            insert_pos_ = self.invisibleRootItem().childCount()
            self.invisibleRootItem().insertChild(insert_pos_, item_title_)
        else:
            self.invisibleRootItem().insertChild(index, item_title_)
        item_widget_ = QTreeWidgetItem()
        item_title_.addChild(item_widget_)
        self.setItemWidget(item_widget_, 0, widget)
        item_widget_.setSizeHint(0, QSize(200, height))
        self._widgetTable[title_] = widget


